# coding=utf-8
# author:xc
# datetime:2018/8/27 17:36

from . import html
from app import util, upload_files
from dbConnection.MysqlConn import Mysql
from flask import request
import MySQLdb


# 评论列表
@html.route('/api/comment/list', methods=['POST', 'GET'])
def api_comment_list():
    try:
        chapterId = request.values.get('chapterId')
        page = request.values.get('page', default=1)
        page = int(page)
        num = (page - 1) * util.PAGE_NUM
        mysql = Mysql()
        sql = "select a.*,b.nickname,b.header from girl_comment as a left join " \
              "girl_teacher as b on a.uid=b.uid where chapterId='%s'and a.status=1 order by a.addTime asc limit %d,%d " % (
                  chapterId, num, util.PAGE_NUM)
        sql1 = "select count(*) from girl_comment where chapterId='%s' and status=1 " % chapterId
        sql2 = "select b.*,c.header,c.nickname,d.nickname as name from girl_comment as a " \
               "left join girl_reply as b on a.commentId=b.commentId left join girl_teacher as" \
               " c on b.uid=c.uid left join girl_teacher as d on d.uid=b.f_uid  where a.chapterId='%s'" \
               " and b.status=1 order by b.addTime asc " % chapterId
        result = mysql.getAll(sql, None)
        res = mysql.getAll(sql2, None)
        count = mysql.getOne(sql1, None)
        mysql.dispose()
        code = util.CODE_EMPTY
        data = []
        if count:
            count = count['count(*)']
            if count % util.PAGE_NUM > 0:
                max_page = count / util.PAGE_NUM + 1
            else:
                max_page = count / util.PAGE_NUM
        else:
            max_page = 0
        if result > 0:
            code = util.CODE_SUCCESS
            for x in result:
                data_comment = dict()
                data_comment['commentId'] = x['commentId']
                data_comment['content'] = x['content']
                data_comment['addTime'] = x['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                data_comment['nickname'] = x['nickname']
                if not x['header'].startswith('http'):
                    data_comment['header'] = upload_files.baseUrl + x['header']
                else:
                    data_comment['header'] = x['header']
                reply = []
                if res:
                    for k in res:
                        if x['commentId'] == k['commentId']:
                            data_reply = dict()
                            data_reply['uid'] = k['uid']
                            data_reply['f_uid'] = k['f_uid']
                            if data_reply['f_uid'] == 0:
                                data_reply['name'] = ""
                            else:
                                data_reply['name'] = k['name']
                            data_reply['content'] = k['content']
                            data_reply['addTime'] = k['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                            data_reply['nickname'] = k['nickname']
                            if not k['header'].startswith("http"):
                                data_reply['header'] = upload_files.baseUrl + k['header']
                            else:
                                data_reply['header'] = x['header']
                            reply.append(data_reply)
                data_comment['res'] = reply
                data.append(data_comment)
    except Exception as e:
        print e
        code = util.CODE_ERROR
        data = []
        max_page = 0
    data = {
        'data': data,
        'code': code,
        'max_page': max_page
    }
    return util.to_json(data)


# 章节评论
@html.route('/api/send/comment', methods=['POST', 'GET'])
@util.verify_login
def api_send_comment(uid):
    try:
        content = request.values.get('content')
        cid = request.values.get('cid')
        chapterId = request.values.get('chapterId')
        mysql = Mysql()
        sql = "insert into girl_comment(cid,chapterId,content,addTime,uid,status) values ('%s','%s','%s',now(),'%s',1)" \
              % (cid, chapterId, MySQLdb.escape_string(content), uid)
        result = mysql.insertOne(sql, None)
        mysql.dispose()
        code = util.CODE_FAIL
        if result > 0:
            code = util.CODE_SUCCESS
    except Exception as e:
        print e
        code = util.CODE_ERROR
    data = {
        'code': code
    }
    return util.to_json(data)


# 评论回复
@html.route('/api/comment/reply', methods=['POST', 'GET'])
@util.verify_login
def api_comment_reply(uid):
    try:
        commentId = request.values.get('commentId')
        f_uid = request.values.get('f_uid', default=0)
        content = request.values.get('content')
        mysql = Mysql()
        print commentId,f_uid,content
        sql = "insert into girl_reply(commentId,uid,f_uid,content,addTime,status) values('%s','%s','%s','%s',now(),1)" % (
            commentId, uid, f_uid, MySQLdb.escape_string(content))
        print sql
        result = mysql.insertOne(sql, None)
        mysql.dispose()
        code = util.CODE_FAIL
        if result > 0:
            code = util.CODE_SUCCESS
    except Exception as e:
        print e
        code = util.CODE_ERROR
    data = {
        'code': code
    }
    return util.to_json(data)
